# -*- coding: utf-8 -*-
import struct
from utils import byteUtil
from utils import bcdUtil

class Packet(object):
    def __init__(self, ctrl=0x0, data=[], uid=None, cs=0, raw=None):
        self._uid = uid
        self._ctrl = ctrl
        self._data = data
        self._dataLen = len(data)
        self._cs = cs

        self._raw = raw


    def encode(self):
        if not self._raw:
            self._raw = []
            self._raw.append(0x68)
            if not self._uid:
                self._uid = (0, 0, 0, 0, 0, 0)

            uid=bcdUtil.hexTobcd(self._uid)
            self._raw.extend(uid)

            self._raw.append(0x68)
            self._raw.append(self._ctrl)

            self._dataLen = len(self._data)
            self._raw.extend(byteUtil.encodeShortBigEndian(self._dataLen))

            self._raw.extend(self._data)

            self.__calcCS__(self._raw)
            self._raw.append(self._cs)
            self._raw.append(0x16)

            return self._raw

    @property
    def uid(self):
        return tuple(self._uid)

    @uid.setter
    def uid(self, value):
        self._uid = value
        self._raw = None

    @property
    def dataLen(self):
        return self._dataLen

    @property
    def dataRegion(self):
        return tuple(self._data)

    @property
    def ctrl(self):
        return self._ctrl

    def pack(self):
        if not self._raw:
            self.encode()
        return struct.pack('B' * len(self._raw), *self._raw)

    def __calcCS__(self, datas):
        cs = 0
        for b in datas:
            cs += b
        cs = cs & 0xff
        self._cs = cs

    def info(self):
        if not self._raw:
            self.encode()

        pack = ""
        i = 0
        for char in self._raw:
            if (i == 8):
                pack += " : "
            if char < 16:
                pack += "0" + hex(char).replace("0x", "") + " ";
            else:
                pack += hex(char).replace("0x", "") + " ";
            i += 1
        return pack.upper()


